package com.jmhy.sdk.activity.View;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.ViewTreeObserver;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.jmhy.sdk.activity.BaseFloatActivity;
import com.jmhy.sdk.common.JiMiSDK;
import com.jmhy.sdk.config.AppConfig;
import com.jmhy.sdk.config.WebApi;
import com.jmhy.sdk.sdk.PayDataRequest;
import com.jmhy.sdk.utils.AndroidBug5497Workaround;
import com.jmhy.sdk.utils.FloatJsInterface;
import com.jmhy.sdk.utils.SecurityUtils;
import com.jmhy.sdk.view.GifImageView;

import java.io.File;
import java.util.ArrayList;

public class FloatUserPayView extends BaseFloatActivity {
    private static final String TAG = "FloatUserPayView";
    private WebView mWebview;
    private GifImageView mGifImageView;

    private String mUrl;


    private int mWbeHeight;

    private View back_view;
    private ImageView ivback;
    private boolean isShowKeyboard;
    private int reduceHeight;
    private CloseFloatListener closeFloatListener;


    private String orderId = "";


    private File file = null;



    public FloatUserPayView(Activity activity, CloseFloatListener listener) {
        super(activity);
        this.closeFloatListener=listener;
    }
    @Override
    public void setContentView(@NonNull int layout_id) {
        super.setContentView(layout_id);
    }



    @Override
    public void setViews( String url) {
        if(contentView!=null){
            return;
        }
        mUrl = url;
        intView();

        //防止软键盘覆盖webview
        mWebview.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Log.d(TAG, "onGlobalLayout: 软键盘状态改变");
                if(mWebview!=null){
                    mWbeHeight = mWebview.getHeight();
                    Rect r = new Rect();
                    //获取当前界面可视部分
                    activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(r);
                    //获取屏幕的高度
                    int screenHeight =  activity.getWindow().getDecorView().getRootView().getHeight();
                    //此处就是用来获取键盘的高度的， 在键盘没有弹出的时候 此高度为0 键盘弹出的时候为一个正数
                    int heightDifference = screenHeight - r.bottom;
                    Log.d("Keyboard Size", "Size: " + heightDifference);
                    FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) mWebview.getLayoutParams();
                    if (heightDifference>150&&!isShowKeyboard){
                        reduceHeight =mWbeHeight-(mWbeHeight-heightDifference) ;
                        layoutParams.height = mWbeHeight-heightDifference;
                        mWebview.setLayoutParams(layoutParams);
                        isShowKeyboard = true;
                    }else if (heightDifference<150&&isShowKeyboard){
                        isShowKeyboard =false;
                        layoutParams.height = mWbeHeight+reduceHeight;
                        mWebview.setLayoutParams(layoutParams);
                    }
                }
            }
        });
    }

    @Override
    public void removeContentView() {
        super.removeContentView();

        if (contentView != null) {
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Log.d(TAG, "removeContentView: threadName" + Thread.currentThread().getName());
                    ViewParent parent = contentView.getParent();
                    ViewGroup viewGroup = (ViewGroup) parent;
                    ViewGroup viewGroup1 = (ViewGroup) contentView;
                    int count = viewGroup1.getChildCount();
                    viewGroup1.removeAllViews();
                    Log.d(TAG, "removeContentView: childCount=" + count);
                    viewGroup.removeView(contentView);
                    mWebview.clearCache(true);
                    mWebview=null;
                    mGifImageView=null;


                    contentView=null;
                    closeFloatListener.closeFloat(orderId);
                }
            });

        }
    }

    @Override
    public void show() {
        super.show();
    }

    @Override
    public boolean isShow() {
        return super.isShow();
    }

    private void intView() {

        int layout_id = 0;



         layout_id=AppConfig.resourceId(activity, "jmuserp_red", "layout");


        setContentView(layout_id);
        if (true) {
            AndroidBug5497Workaround.assistActivity(activity);
        }
        // TODO Auto-generated method stub
        ivback = contentView.findViewById((AppConfig.resourceId(activity, "ivback", "id")));
        ivback.setOnClickListener(this);

        back_view =contentView.findViewById((AppConfig.resourceId(activity, "back_view", "id")));
        back_view.setOnClickListener(this);


        mWebview = (WebView) contentView.findViewById(AppConfig.resourceId(activity,
                "webview", "id"));
        mGifImageView = (GifImageView) contentView.findViewById(AppConfig.resourceId(activity,
                "gif", "id"));

        setLoadingGifImg();

        View view = contentView.findViewById(AppConfig.resourceId(activity,
                "content", "id"));
        //测试view是否为空
        if (view == null) {
            Log.e("JiMiSDK", "JmuserinfoActivity view == null");
            return;
        }
        switch (AppConfig.skin) {
            case 5:
            case 4:
                //layoutParams.width = (int)getResources().getDimension(AppConfig.resourceId(activity, "jm_login_width_4", "dimen"));
                //layoutParams.height = (int)getResources().getDimension(AppConfig.resourceId(activity, "jm_login_height_4", "dimen"));
                break;
        }
//        mWebview.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        mWebview.setVerticalScrollBarEnabled(false);
        mWebview.getSettings().setSupportZoom(false);
        mWebview.getSettings().setSaveFormData(false);
        mWebview.getSettings().setSavePassword(false);
        mWebview.getSettings().setJavaScriptEnabled(true);
        mWebview.getSettings().setBuiltInZoomControls(false);
        mWebview.getSettings().setSupportZoom(false);
        mWebview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);// 默认不使用缓存！
        mWebview.addJavascriptInterface(new FloatJsInterface(activity, this), "jimiJS");
        mWebview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);

        mWebview.getSettings().setTextZoom(100);


        // 修复一些机型webview无法点击****/
        mWebview.requestFocus(View.FOCUS_DOWN);
        mWebview.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                Log.i(TAG, "onPageStarted " + url);
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                Log.i(TAG, "onPageFinished " + url);
                super.onPageFinished(view, url);
                hiddenLoading();
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log.i("JiMiSDK","shouldOverrideUrlLoading "+url);
                String lowcaseUrl = url.toLowerCase();
                if (lowcaseUrl.startsWith("weixin://wap/pay")) {
                    try {
                        Intent intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
                        view.getContext().startActivity(intent);

                        refreshPay();
                    } catch (Exception e) {
                        e.printStackTrace();
                        removeContentView();
                    }

                    return true;
                } else if (lowcaseUrl.startsWith("alipays://platformapi/startapp")){
                    try {
                        Log.i("JiMiSDK", "uuuuuuuuuuuuu");

                        Intent intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
                        view.getContext().startActivity(intent);

                        refreshPay();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return true;
                } else {

                    return false;
                }
            }
        });
        mWebview.setWebChromeClient(new WebChromeClient());
        mWebview.loadUrl(mUrl);
    }


    private void refreshPay(){
        String url = WebApi.BASE_HOST + "/pay_back/info?access_token={access_token}&billno={billno}";
        url = url.replace("{access_token}", AppConfig.Token);
        url = url.replace("{billno}", PayDataRequest.getmPayInfo().getCporderid());
        mWebview.loadUrl(url);

        Log.i(TAG, "url = " + url);
    }

    public void hiddenLoading() {
        Log.i(TAG, "loadingamimation a");
        if (mGifImageView == null) {
            return;
        }
        Log.i(TAG, "loadingamimation b");
        mGifImageView.pause();
        mGifImageView.setVisibility(View.INVISIBLE);
    }



    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        if (v.getId() == AppConfig.resourceId(activity, "iphoneback", "id")) {
            if (mWebview.canGoBack()) {
                mWebview.goBack();
            } else {
                // TODO Auto-generated method stub
            }
        }  else if (v.getId() ==AppConfig.resourceId(activity, "ivback", "id") ) {
            removeContentView();

        } else if (v.getId() ==AppConfig.resourceId(activity, "back_view", "id") ) {
//            if (AppConfig.skin==9){//皮肤9点背景层关闭浮窗
//                removeContentView();
//                closeFloatListener.closeFloat();
//            }
        }
    }


    public interface CloseFloatListener {

        void closeFloat(String orderId);

    }

    @Override
    public void closeAnimation() {
        super.closeAnimation();
        hiddenLoading();
    }

    /***
     * 1.4.4新增
     */
    private void setLoadingGifImg(){
        if (isExistsLoadingImg(AppConfig.webLoadingUrl)){

            Glide.with(activity).load(this.file).dontTransform().into(this.mGifImageView);
        }else {
            if (AppConfig.float_gift.equals("1")){

                Glide.with(activity).load(AppConfig.resourceId(activity, "jmloading_red",
                        "drawable")).dontTransform().into(this.mGifImageView);

            }else{

                Glide.with(activity).load(AppConfig.resourceId(activity, "jmloading_new",
                        "drawable")).dontTransform().into(this.mGifImageView);
            }
        }
    }


    private boolean isExistsLoadingImg(String url) {
        if (url == null || url.equals("")) {
            return false;
        }
        String md5ResultString = SecurityUtils.getMD5Str(url);
        if (this.file == null) {
            if (Build.VERSION.SDK_INT < 29) {
                this.file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "Camera");
            } else {
                this.file = JiMiSDK.mContext.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
            }
            this.file = new File(this.file + "/" + md5ResultString + ".gif");
        }

        if (!this.file.exists()) {
            return false;
        }

        return true;
    }

    @Override
    public void paymentOrder(String order) {
        super.paymentOrder(order);
        this.orderId = order;
    }
}
